#!/usr/bin/env bash
# Copyright (c) 2024 Huawei Device Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

set -e
project_root= #"/home/android/project/xxxxx"
project_out_obj="${project_root}/out/rk3568/obj"
openvpn_root=`pwd`
lz4_path="$project_root/third_party/lz4"
lz4_obj_path="$project_out_obj/third_party/lz4"
openssl_path="$project_root/third_party/openssl"
openssl_obj_path="$project_out_obj/third_party/openssl"

selected_platform="linux-armv4"
openvpn_out_obj_path="${openvpn_root}/${selected_platform}"

# delete the old output files
rm -rf ${openvpn_out_obj_path}

# Check if source dir exists
directories=($lz4_obj_path $openssl_obj_path)
for dir in "${directories[@]}"; do
    if [ ! -d "$dir" ]; then
        echo "error: $dir not exist. pls set project_root path"
        exit 1
    fi
done

# touch an empty openvpn file for syntax check by build.gn 
mkdir -p ${openvpn_out_obj_path}/sbin
touch ${openvpn_out_obj_path}/sbin/openvpn
chmod 777 ${openvpn_out_obj_path}/sbin/openvpn

export OHOS_TOOLCHAIN=${project_root}/prebuilts/clang/ohos/linux-x86_64/llvm
export OHOS_SYSROOT=${project_out_obj}/third_party/musl

export CC=${OHOS_TOOLCHAIN}/bin/clang
export CPP="${OHOS_TOOLCHAIN}/bin/clang -E"
export AR=${OHOS_TOOLCHAIN}/bin/llvm-ar
export AS=${OHOS_TOOLCHAIN}/bin/llvm-as
export NM=${OHOS_TOOLCHAIN}/bin/llvm-nm
export STRIP=${OHOS_TOOLCHAIN}/bin/llvm-strip
export RANLIB=${OHOS_TOOLCHAIN}/bin/llvm-ranlib
export LD=${OHOS_TOOLCHAIN}/bin/ld.lld
export LDFLAGS="--rtlib=compiler-rt -fuse-ld=lld"
export CFLAGS="-O3 -D__MUSL__ -DSUPPORT_SYSVPN --target=arm-linux-ohos --sysroot=${OHOS_SYSROOT} -march=armv7-a -mfloat-abi=softfp"

pushd ${openvpn_root}
./configure \
--target=arm-linux-gnueabi \
--host=arm-linux-gnueabi \
--prefix=${openvpn_out_obj_path} \
--enable-static \
--disable-shared \
--disable-debug \
--disable-dco \
--disable-plugins \
--disable-lzo \
OPENSSL_LIBS="-L${openssl_obj_path} -lssl_static -lcrypto_static" \
OPENSSL_CFLAGS="-I${openssl_obj_path}/build_all_generated/${selected_platform}/include -I${openssl_path}/include" \
LZ4_CFLAGS="-I${lz4_path}/lib" \
LZ4_LIBS="-L${lz4_obj_path} -llz4_static"
make clean && make LIBS="-all-static" && make install -j24 >/dev/null 2>&1
$STRIP ${openvpn_out_obj_path}/sbin/openvpn
popd
